//
//  XQABManager.m
//  AddressBook
//
//  Created by ladystyle100 on 2017/5/6.
//  Copyright © 2017年 WangXQ. All rights reserved.
//

#import "XQABUIManager.h"
#import "XQABHeader.h"

#import <AddressBookUI/ABPeoplePickerNavigationController.h>// 9.0以下
#import <AddressBook/ABPerson.h>
#import <AddressBook/AddressBook.h>// 获取通讯录信息

#import <ContactsUI/ContactsUI.h>// 9.0以上


@interface XQABUIManager () <CNContactPickerDelegate, ABPeoplePickerNavigationControllerDelegate>

@property (nonatomic, strong) CNContactPickerViewController *peoplePickVC;// 9.0以上
@property (nonatomic, strong) ABPeoplePickerNavigationController *nav;// 9.0以下

@end

static XQABUIManager *_manager = nil;

@implementation XQABUIManager

+ (instancetype)sharedXQABManager {
    if (!_manager) {
        _manager = [[XQABUIManager alloc] init];
        
    }
    return _manager;
}

- (void)presentABWithVC:(UIViewController *)VC {
    if ([VC respondsToSelector:@selector(presentViewController:animated:completion:)]) {
        // 判断当前系统版本，然后选中不同的控制器跳转
        if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0) {
            [VC presentViewController:self.peoplePickVC animated:YES completion:nil];
        }else {
            [VC presentViewController:self.nav animated:YES completion:nil];
        }
    }
}

// 取消
- (void)cancel {
    if ([self.delegate respondsToSelector:@selector(ABDidCancel)]) {
        [self.delegate ABDidCancel];
    }
}

// 选中
- (void)selectPhoneStr:(NSString *)phoneStr nameStr:(NSString *)nameStr {
    if ([self.delegate respondsToSelector:@selector(ABDidSelecetWithPhoneStr:nameStr:)]) {
        [self.delegate ABDidSelecetWithPhoneStr:phoneStr nameStr:nameStr];
    }
}

// 删除多余字符串
- (NSString *)deleteSuperfluous:(NSString *)phoneStr {
    // 除去国家前三位
    if ([phoneStr hasPrefix:@"+"]) {
        phoneStr = [phoneStr substringFromIndex:3];
    }
    // 除去-
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    return phoneStr;
}


// 选中只能发生一个事件，当级别高时，就表示同时声明，以它为主
#pragma mark -- CNContactPickerDelegate

// 点击取消
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
    [self cancel];
}

// 点击联系人，级别1
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    NSString *nameStr = nil;
    NSString *phoneStr = nil;
    
    // 名
    NSString *firstName = contact.givenName;
    // 姓
    NSString *lastName = contact.familyName;
    if (!firstName) {
        firstName = @"";
    }
    
    if (!lastName) {
        lastName = @"";
    }
    
    //获取联系人姓名
    nameStr = [NSString stringWithFormat:@"%@%@", contact.familyName, contact.givenName];
    
    //数组保存各种类型的联系方式的字典（可以理解为字典） 字典的key和value分别对应号码类型和号码
    NSArray * phoneNums = contact.phoneNumbers;
    
    //通过遍历获取联系人各种类型的联系方式
    for (CNLabeledValue *labelValue in phoneNums) {
        // 电话描述
//        NSString *phoneLabel = labelValue.label;
        // 当前电话
        NSString *currentPhoneStr = [self deleteSuperfluous:[labelValue.value stringValue]];
        // 判断是否符合手机号码格式
        phoneStr = currentPhoneStr;
        break;
    }
    
    [self selectPhoneStr:phoneStr nameStr:nameStr];
}

/*
// 点击联系人详细信息，级别0
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    NSString *nameStr = nil;
    NSString *phoneStr = nil;
    
    [self selectPhoneStr:phoneStr nameStr:nameStr];
}
 */


// 选中只能发生一个事件，当级别高时，就表示同时声明，以它为主
#pragma mark -- ABPeoplePickerNavigationControllerDelegate

// 点击取消
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [self cancel];
}

// 点击联系人，级别1
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
    NSString *nameStr = nil;
    NSString *phoneStr = nil;
    // 名
    NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    // 姓
    NSString *lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (!firstName) {
        firstName = @"";
    }
    
    if (!lastName) {
        lastName = @"";
    }
    
    nameStr = [NSString stringWithFormat:@"%@%@", lastName, firstName];
    
    // 获得电话号码的多值对象
    ABMultiValueRef values = ABRecordCopyValue(person, kABPersonPhoneProperty);
    // 获取有多少个电话号码
    NSInteger index = ABMultiValueGetCount(values);
    for (int i = 0; i < index; i++) {
        // 获取当前电话号码
        NSString *currentPhoneStr = (__bridge NSString *)ABMultiValueCopyValueAtIndex(values, i);
        // 删除多余符合的数字
        currentPhoneStr = [self deleteSuperfluous:currentPhoneStr];
        // 是否符合手机号码格式
        phoneStr = currentPhoneStr;
        //break;
    }
    
    //释放资源
    CFRelease(values);
    [self selectPhoneStr:phoneStr nameStr:nameStr];
}

// 点击联系人的详细信息，级别0
/**
 * @prama person 选择的联系人
 * @prama property 选择的属性ID
 * @prama identifier 选择的属性下标
 */
/*
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    NSString *nameStr = nil;
    NSString *phoneStr = nil;
    
    if (property == kABPersonPhoneProperty) {
        // 名
        NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        // 姓
        NSString *lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
        nameStr = [NSString stringWithFormat:@"%@%@", lastName, firstName];
        
        // 获得电话号码的多值对象
        ABMultiValueRef values = ABRecordCopyValue(person, kABPersonPhoneProperty);
        // 根据用户点击的下标电话号码
        NSString *idenPhoneStr = [self deleteSuperfluous:(__bridge NSString *)ABMultiValueCopyValueAtIndex(values, identifier)];
        // 删除多余符合的数字
        idenPhoneStr = [self deleteSuperfluous:idenPhoneStr];
        // 是否符合手机号码格式
        if ([ValidatingManager validatePhone:idenPhoneStr]) {
            phoneStr = idenPhoneStr;
        }
        
        //释放资源
        CFRelease(values);
    }
    
    [self selectPhoneStr:phoneStr nameStr:nameStr];
}
 */

#pragma mark -- get

- (CNContactPickerViewController *)peoplePickVC {
    if (!_peoplePickVC) {
        _peoplePickVC = [[CNContactPickerViewController alloc] init];
        _peoplePickVC.delegate = self;
    }
    return _peoplePickVC;
}

- (ABPeoplePickerNavigationController *)nav {
    if (!_nav) {
        _nav = [[ABPeoplePickerNavigationController alloc] init];
        _nav.peoplePickerDelegate = self;
    }
    return _nav;
}

@end














